package com.zang.blogz.service.impl;

import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zang.blogz.constant.AuthorConstant;
import com.zang.blogz.constant.ResultConstant;
import com.zang.blogz.entity.JobLog;
import com.zang.blogz.mapper.JobLogMapper;
import com.zang.blogz.model.output.JobLogVO;
import com.zang.blogz.result.Result;
import com.zang.blogz.service.JobLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.vampireachao.stream.core.optional.Opp;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 定时任务调度日志表 服务实现类
 * </p>
 *
 * @author 朵橙i
 * @since 2022-09-04
 */
@Service
public class JobLogServiceImpl extends ServiceImpl<JobLogMapper, JobLog> implements JobLogService {

    @Override
    public IPage<JobLog> queryJobLogList(IPage<JobLog> iPage, QueryWrapper<JobLog> queryWrapper) {

        IPage<JobLog> page = page(iPage, queryWrapper);

        return page.convert(result->{

            JobLogVO vo = new JobLogVO();

            BeanUtil.copyProperties(result, vo);
            return vo;
        });
    }

    @Override
    public Result<Boolean> deleteByIds(List<Integer> ids) {

        isCan();

        LambdaQueryWrapper<JobLog> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.in(JobLog::getId, ids);

        int oldSize = list(queryWrapper).size();

        if (ids.size() != oldSize){

            throw new RuntimeException(ResultConstant.DELETE_FAIL);
        }

        boolean b = removeByIds(ids);

        if (b){

           return Result.ok(ResultConstant.DELETE_SUCCESS);
        }
        return Result.error(ResultConstant.DELETE_FAIL);
    }

    @Override
    public Result<Boolean> deleteById(Integer id) {

        isCan();

        detailed(id);

        boolean removeById = removeById(id);

        if (removeById){

            return Result.ok(ResultConstant.DELETE_SUCCESS, Boolean.TRUE);
        }

        return Result.error(ResultConstant.DELETE_FAIL, Boolean.FALSE);
    }

    @Override
    public Result<JobLog> detailed(Integer id) {

        JobLog byId = getById(id);

        if (Opp.of(byId).isEmpty()){

            throw new RuntimeException("当前日志不存在");
        }

        return Result.ok(byId);
    }


    private void isCan(){

        String name = (String) StpUtil.getExtra("name");

        boolean contains = AuthorConstant.authorSet.contains(name);

        if (!contains) {

            throw new NotPermissionException("你没有当前权限不能删除日志");
        }
    }


}
